from flask import current_app, jsonify
from flask import render_template
from flask import request
from flask import session

from info import constants
from info.models import User, News, Category
from info.response_code import RET
from . import index_blu


@index_blu.route("/")
def index():
    title = "新经资讯网-首页"
    # 获取当前登录用户的id
    user_id = session.get("user_id")
    # print(user_id)
    # 通过id获取用户信息
    user = None
    if user_id:
        try:
            user = User.query.get(user_id)
        except Exception as e:
            current_app.logger.error(e)
    # print(user)

    # 获取点击排行数据
    news_clicks = None
    try:
        news_clicks = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    except Exception as e:
        current_app.logger.error(e)

    # 获取新闻分类数据
    categorys = Category.query.all()

    return render_template("news/index.html", title=title,
                           user=user,
                           news_clicks=news_clicks,
                           categorys=categorys)


@index_blu.route("/favicon.ico")
def favicon():
    # send_static_file 帮我们自动到static目录下读取对应的文件的内容
    return current_app.send_static_file('news/favicon.ico')


@index_blu.route("/news_list")
def news_list():
    """ajax请求新闻列表数据"""
    # 1.接受参数并校验
    data_dict = request.args
    page = data_dict.get("page", 1)   # 当前页码
    cid = data_dict.get("cid", 1)   # 新闻分类id
    per_page = data_dict.get("per_page", constants.HOME_PAGE_MAX_NEWS)   # 允许每一页展示的数据量
    try:
        page = int(page)
        per_page = int(per_page)
        cid = int(cid)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    # 2.获取数据
    filters = []
    if cid != 1:
        # 根据指定的分类id来查询新闻列表
        filters.append(News.category_id == cid)
    try:
        paginate = News.query.filter(*filters).order_by(News.id.desc()).paginate(int(page), per_page, False)
        # 获取查询出来的数据[items是一个列表，列表中的每一个成员都是模型对象]
        items = paginate.items
        # 获取总页数
        total_page = paginate.pages
        # 当前页码
        current_page = paginate.page
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR, errmsg="数据查询失败")

    # 3.返回数据之前需要把每一个模型对象转换成字典格式，因为js不识别python的模型对象
    news_dict_list = []
    for news in items:
        news_dict_list.append(news.to_basic_dict())

    # 4.返回结果
    return jsonify(errno=RET.OK, errmsg="OK",
                   totalPage=total_page,
                   currentPage=current_page,
                   newsList=news_dict_list,
                   cid=cid)